package com.creditfamily.ruleEngine.drools.utils;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.drools.core.impl.KnowledgeBaseImpl;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.creditfamily.ruleEngine.drools.engine.EngineHelper;
import com.creditfamily.ruleEngine.drools.engine.dto.CheckParam;
import com.creditfamily.ruleEngine.drools.engine.dto.ResultDetail;
import com.creditfamily.ruleEngine.drools.engine.dto.RuleGroup;
import com.creditfamily.ruleEngine.drools.engine.dto.RuleResult;
import com.creditfamily.ruleEngine.drools.facet.RiskInfo;
import com.creditfamily.ruleEngine.drools.filter.RuleAgendaFilter;

import lombok.extern.slf4j.Slf4j;

/**
 * @author SXF
 * 2018年12月18日 15:11
 */
@Slf4j
public class RuleEngineUtil {

    public static RuleResult checkUser(CheckParam checkParam, RuleGroup ruleGroup, List<Map<String, Object>> executeRules) {
        RuleResult result = new RuleResult();
        KieSession session = null;
        String cacheKey = null;
        try {
            result.setDetailList(new LinkedList<>());
            if (CollectionUtils.isNotEmpty(executeRules)) {
//                List<Map<String, Object>> rules = executeRules.stream().filter(map ->
//                        map.get("ruleDecision").equals(ruleGroup.getStopAt())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(executeRules)) {
                    RiskInfo riskInfo = new RiskInfo();
                    riskInfo.setCheckParam(checkParam);
                    String extendData = checkParam.getExtendData();
                    if (StringUtils.isNotEmpty(extendData)) {
                        JSONObject extendInfo = JSONObject.parseObject(extendData);
                        extendInfo.put("phone", checkParam.getPhone());
                        riskInfo.setExtendInfo(extendInfo);
                    }
                    cacheKey = String.valueOf(IdWorker.getId());
                    Thread.currentThread().setName(cacheKey);
                    EngineHelper.setParamInfo(cacheKey, checkParam);
                    EngineHelper.setRunInfo(cacheKey, result);
                    String ruleCode;
                    KnowledgeBaseImpl kieBase = (KnowledgeBaseImpl) EngineHelper.getKieContainer().getKieBase();
                    session = kieBase.newKieSession();
                    FactHandle handle = session.insert(riskInfo);
                    for (Map<String, Object> rule : executeRules) {
                        ruleCode = (String) rule.get("ruleCode");

                        result.setCurrentCode(ruleCode);
                        ResultDetail resultDetail = new ResultDetail();
                        resultDetail.setRuleCode(ruleCode);
                        resultDetail.setRuleName((String) rule.get("ruleName"));
                        resultDetail.setRuleDesc((String) rule.get("ruleDesc"));
                        result.getDetailList().add(resultDetail);

                        riskInfo.setCurrentRuleCode(ruleCode);
                        session.update(handle, riskInfo);

                        int count = session.fireAllRules(new RuleAgendaFilter(
                                (String) rule.get("rulePackage"), ruleCode));
                        if (count > 0 && ruleGroup.getStopAt().equals(rule.get("ruleDecision"))) {
                            result.setHitRule(true);
                            resultDetail.setHitRule(true);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            if (Integer.valueOf(460).equals(result.getCode())) {
                log.info("access_token 失效");
            } else {
                log.error("规则执行失败:", e);
                result.setCode(500);
            }
        } finally {
            try {
                if (session != null) {
                    session.destroy();
                }
            } catch (Exception e){
                log.info("session destroy failed", e);
            }
            if (StringUtils.isNotEmpty(cacheKey)) {
                EngineHelper.removeParamInfo(cacheKey);
                EngineHelper.removeRunInfo(cacheKey);
            }
        }
        return result;
    }
}
